package com.dimples.dd.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dimples.dd.common.enums.CommonStatusEnum;
import com.dimples.dd.common.exception.ErrorCode;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.system.convert.SmsTemplateConvert;
import com.dimples.dd.system.core.dal.redis.RedisKeyConstants;
import com.dimples.dd.system.framework.sms.core.client.SmsClient;
import com.dimples.dd.system.framework.sms.core.client.dto.SmsTemplateRespDTO;
import com.dimples.dd.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum;
import com.dimples.dd.system.mapper.SystemSmsTemplateMapper;
import com.dimples.dd.system.model.entity.SystemSmsTemplateDO;
import com.dimples.dd.system.model.form.SmsChannelForm;
import com.dimples.dd.system.model.form.SmsTemplateForm;
import com.dimples.dd.system.model.query.SmsTemplatePageQuery;
import com.dimples.dd.system.model.vo.SmsTemplatePageVO;
import com.dimples.dd.system.service.SystemSmsChannelService;
import com.dimples.dd.system.service.SystemSmsTemplateService;
import com.dimples.dd.system.service.SystemUsersService;
import com.google.common.annotations.VisibleForTesting;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.dimples.dd.common.exception.BizExceptionUtil.exception;
import static com.dimples.dd.common.exception.ErrorCode.SMS_TEMPLATE_CODE_DUPLICATE;
import static com.dimples.dd.common.exception.ErrorCode.SMS_TEMPLATE_NOT_EXISTS;

@Service
@RequiredArgsConstructor
public class SystemSmsTemplateServiceImpl extends ServiceImpl<SystemSmsTemplateMapper, SystemSmsTemplateDO> implements SystemSmsTemplateService {

    private final SmsTemplateConvert smsTemplateConvert;
    private final SystemUsersService systemUsersService;

    @Resource
    private SystemSmsChannelService systemSmsChannelService;

    /**
     * 正则表达式，匹配 {} 中的变量
     */
    private static final Pattern PATTERN_PARAMS = Pattern.compile("\\{(.*?)}");

    @Override
    public Long selectSmsTemplateCountByChannelId(Long channelId) {
        return this.baseMapper.selectCount(SystemSmsTemplateDO::getChannelId, channelId);
    }

    @Override
    public Long createSmsTemplate(SmsTemplateForm createSmsTemplateForm) {
        // 校验短信渠道
        SmsChannelForm channelForm = validateSmsChannel(createSmsTemplateForm.getChannelId());
        // 校验短信编码是否重复
        createSmsTemplateForm.setCode("T_SMS_" + IdUtil.getSnowflakeNextIdStr());
        validateSmsTemplateCodeDuplicate(null, createSmsTemplateForm.getCode());
        // 校验短信模板
        validateApiTemplate(createSmsTemplateForm.getChannelId(), createSmsTemplateForm.getApiTemplateId());

        // 插入
        SystemSmsTemplateDO template = this.smsTemplateConvert.form2Entity(createSmsTemplateForm);
        template.setParams(parseTemplateContentParams(template.getContent()));
        template.setChannelCode(channelForm.getCode());
        template.setCreateTime(null);
        this.baseMapper.insert(template);
        // 返回
        return template.getId();
    }

    @CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE, allEntries = true) // allEntries 清空所有缓存，因为 id 不是直接的缓存 code，不好清理
    @Override
    public void updateSmsTemplate(SmsTemplateForm updateSmsTemplateForm) {
        // 校验存在
        validateSmsTemplateExists(CollUtil.newArrayList(updateSmsTemplateForm.getId()));
        // 校验短信渠道
        SmsChannelForm channelDO = validateSmsChannel(updateSmsTemplateForm.getChannelId());
        // 校验短信编码是否重复
        validateSmsTemplateCodeDuplicate(updateSmsTemplateForm.getId(), updateSmsTemplateForm.getCode());
        // 校验短信模板
        validateApiTemplate(updateSmsTemplateForm.getChannelId(), updateSmsTemplateForm.getApiTemplateId());

        // 更新
        SystemSmsTemplateDO updateObj = this.smsTemplateConvert.form2Entity(updateSmsTemplateForm);
        updateObj.setParams(parseTemplateContentParams(updateObj.getContent()));
        updateObj.setChannelCode(channelDO.getCode());
        this.baseMapper.updateById(updateObj);
    }

    @CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE, allEntries = true) // allEntries 清空所有缓存，因为 id 不是直接的缓存 code，不好清理
    @Override
    public void deleteSmsTemplate(String id) {
        List<String> ids = StrUtil.split(id, StrUtil.COMMA);
        // 校验存在
        validateSmsTemplateExists(ids.stream().map(Long::valueOf).collect(Collectors.toList()));
        // 更新
        this.baseMapper.deleteById(id);
    }

    @Override
    public SmsTemplateForm selectSmsTemplate(Long id) {
        return this.smsTemplateConvert.entity2Form(this.baseMapper.selectById(id));
    }

    @Override
    public PageResult<SmsTemplatePageVO> selectSmsTemplatePage(SmsTemplatePageQuery pageQuery) {
        PageResult<SystemSmsTemplateDO> pageResult = this.baseMapper.selectPage(pageQuery);
        return this.smsTemplateConvert.entity2Page(pageResult);
    }

    @Override
    public String formatSmsTemplateContent(String content, Map<String, Object> params) {
        return StrUtil.format(content, params);
    }

    @Cacheable(cacheNames = RedisKeyConstants.SMS_TEMPLATE, key = "#templateCode", unless = "#result == null")
    @Override
    public SystemSmsTemplateDO selectSmsTemplateByCodeFromCache(String templateCode) {
        return this.baseMapper.selectByCode(templateCode);
    }

    private void validateSmsTemplateExists(List<Long> ids) {
        List<SystemSmsTemplateDO> templateDOList = this.baseMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(templateDOList)) {
            throw exception(SMS_TEMPLATE_NOT_EXISTS, StrUtil.join(StrUtil.COMMA, ids));
        }
        List<Long> existsId = templateDOList.stream().map(SystemSmsTemplateDO::getId).toList();
        List<Long> subtractToList = CollUtil.subtractToList(ids, existsId);
        if (CollUtil.isNotEmpty(subtractToList)) {
            throw exception(SMS_TEMPLATE_NOT_EXISTS, StrUtil.join(StrUtil.COMMA, subtractToList));
        }
    }

    @VisibleForTesting
    public SmsChannelForm validateSmsChannel(Long channelId) {
        SmsChannelForm channelForm = this.systemSmsChannelService.selectSmsChannel(channelId);
        if (channelForm == null) {
            throw exception(ErrorCode.SMS_CHANNEL_NOT_EXISTS);
        }
        if (CommonStatusEnum.isDisable(channelForm.getStatus())) {
            throw exception(ErrorCode.SMS_CHANNEL_DISABLE);
        }
        return channelForm;
    }

    @VisibleForTesting
    public void validateSmsTemplateCodeDuplicate(Long id, String code) {
        SystemSmsTemplateDO template = this.baseMapper.selectByCode(code);
        if (template == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的字典类型
        if (id == null) {
            throw exception(SMS_TEMPLATE_CODE_DUPLICATE, code);
        }
        if (!template.getId().equals(id)) {
            throw exception(SMS_TEMPLATE_CODE_DUPLICATE, code);
        }
    }

    /**
     * 校验 API 短信平台的模板是否有效
     *
     * @param channelId     渠道编号
     * @param apiTemplateId API 模板编号
     */
    @VisibleForTesting
    void validateApiTemplate(Long channelId, String apiTemplateId) {
        // 获得短信模板
        SmsClient smsClient = this.systemSmsChannelService.getSmsClient(channelId);
        Assert.notNull(smsClient, String.format("短信客户端(%d) 不存在", channelId));
        SmsTemplateRespDTO template;
        try {
            template = smsClient.getSmsTemplate(apiTemplateId);
        } catch (Throwable ex) {
            throw exception(ErrorCode.SMS_TEMPLATE_API_ERROR, ExceptionUtil.getRootCauseMessage(ex));
        }
        // 校验短信模版
        if (template == null) {
            throw exception(ErrorCode.SMS_TEMPLATE_API_NOT_FOUND);
        }
        if (Objects.equals(template.getAuditStatus(), SmsTemplateAuditStatusEnum.CHECKING.getStatus())) {
            throw exception(ErrorCode.SMS_TEMPLATE_API_AUDIT_CHECKING);
        }
        if (Objects.equals(template.getAuditStatus(), SmsTemplateAuditStatusEnum.FAIL.getStatus())) {
            throw exception(ErrorCode.SMS_TEMPLATE_API_AUDIT_FAIL, template.getAuditReason());
        }
        Assert.equals(template.getAuditStatus(), SmsTemplateAuditStatusEnum.SUCCESS.getStatus(),
                String.format("短信模板(%s) 审核状态(%d) 不正确", apiTemplateId, template.getAuditStatus()));
    }

    @VisibleForTesting
    List<String> parseTemplateContentParams(String content) {
        return ReUtil.findAllGroup1(PATTERN_PARAMS, content);
    }
}
